import { createRouter, createWebHistory } from "vue-router";
import useSettingsStore from "@/store/modules/settings";
import { getToken } from "@/utils/auth";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: "/", redirect: "/index" },
    {
      path: "/index",
      name: "Index",
      meta: { title: "门诊", keepAlive: true },
      component: () => import("@/views/index/index.vue"),
    },
    {
      path: "/login",
      name: "Login",
      meta: { title: "登录" },
      component: () => import("@/views/login/index.vue"),
    },
    {
      path: "/examination",
      name: "Examination",
      meta: { title: "体检" },
      component: () => import("@/views/examination/index.vue"),
    },
    {
      path: "/hospitalized",
      name: "Hospitalized",
      meta: { title: "住院" },
      component: () => import("@/views/hospitalized/index.vue"),
    },
    {
      path: "/doctorStation",
      name: "DoctorStation",
      meta: { title: "住院" },
      component: () => import("@/views/index/doctorStation/index.vue"),
    },
    {
      // 配置404页面
      path: "/:catchAll(.*)",
      name: "NotFound",
      component: () => import("@/views/exception/NotFound.vue"),
    },
  ],
  // scrollBehavior: () => ({ left: 0, top: 0 }),
  scrollBehavior(to, from, savePosition) {
    // console.log('savePosition:', savePosition);
    if (savePosition) {
      // 解决页面从列表页跳转到详情页返回,初始在原来位置
      return savePosition;
    } else {
      // 解决页面跳转后页面高度和前一个页面高度一样
      return { left: 0, top: 0 };
    }
  },
});

// 导航守卫
router.beforeEach((to, from, next) => {
  const settingsStore = useSettingsStore();
  const token = getToken();
  if (to.path === '/login') {
    if (token) {
      next('/'); // 已登录，重定向到主页
    } else {
      next(); // 未登录，正常导航到登录页
    }
  } else {
    if (!token) {
      next('/login'); // 未登录，重定向到登录页
    } else {
      next(); // 已登录，正常导航
    }
  }
  
  // if (to.path === '/login') {
  //   if (getToken()) {
  //     next('/'); // 已登录，重定向到主页
  //   } else {
  //     next(); // 未登录，正常导航到登录页
  //   }
  // } else {
  //   if (!getToken()) {
  //     next('/login'); // 未登录，重定向到登录页
  //   } else {
  //     next(); // 已登录，正常导航
  //   }
  // }
});

export default router;
